package com.ruicar.afs.cloud.risk.tortoise.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.risk.api.dto.tortoise.request.GwtExposureData;
import com.ruicar.afs.cloud.risk.api.dto.tortoise.request.TortoiseExposurePerson;
import com.ruicar.afs.cloud.risk.api.dto.tortoise.request.TortoiseExposureReq;
import com.ruicar.afs.cloud.risk.tortoise.components.GwtInnerServerRequest;
import com.ruicar.afs.cloud.risk.tortoise.components.GwtTortoiseProcessors;
import com.ruicar.afs.cloud.risk.tortoise.consts.GwtTortoiseConst;
import com.ruicar.afs.cloud.risk.tortoise.dto.notice.GwtTortoiseReq;
import com.ruicar.afs.cloud.risk.tortoise.dto.request.GwtTortoiseExposurePerson;
import com.ruicar.afs.cloud.risk.tortoise.dto.request.GwtTortoiseExposureReq;
import com.ruicar.afs.cloud.risk.tortoise.dto.request.GwtTortoiseImage;
import com.ruicar.afs.cloud.risk.tortoise.dto.response.GwtTortoiseResponse;
import com.ruicar.afs.cloud.risk.tortoise.entity.CreditTortoiseRecord;
import com.ruicar.afs.cloud.risk.tortoise.enums.GwtTortoiseImageType;
import com.ruicar.afs.cloud.risk.tortoise.service.AfsCreditTortoiseRecordService;
import com.ruicar.afs.cloud.risk.tortoise.util.SignPictureUtil;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * Description
 * Author Peng Jinbo
 * Date 2020/07/21 13:54
 */
@RestController
@Slf4j
@AllArgsConstructor
@Api("玄武系统调用")
public class GwtTortoiseCallController {

    /**
     * Gwt tortoise processor
     */
    private GwtTortoiseProcessors gwtTortoiseProcessor;

    private GwtInnerServerRequest gwtInnerServerRequest;

    private AfsCreditTortoiseRecordService afsCreditTortoiseRecordService;

    /**
     * Author Peng Jinbo
     * Callback string
     *
     * @param reqBody req body
     * @return the string
     */
    @PostMapping(GwtTortoiseConst.TORTOISE_CALLBACK_URI)
    public GwtTortoiseResponse queryAndNotice(@RequestBody GwtTortoiseReq reqBody) {
        try {
            return gwtTortoiseProcessor.process(reqBody);
        }catch (Exception e){
            log.error("数据查询/结果通知异常：",e);
            return GwtTortoiseResponse.err(e.getMessage());
        }
    }

    @PostMapping("/tortoise/apis/image")
    public GwtTortoiseResponse image(@RequestBody GwtTortoiseImage imageReq) {
        try {
            log.info("面签照片获取 ==> {}",imageReq );
            String mainId = imageReq.getMainId();
            Optional<CreditTortoiseRecord> recordOptional = afsCreditTortoiseRecordService.list(
                    Wrappers.<CreditTortoiseRecord>lambdaQuery()
                            .eq(CreditTortoiseRecord::getMainId, mainId)
            ).stream().findAny();
            if(recordOptional.isPresent()) {
                CreditTortoiseRecord record = recordOptional.get();
                IResponse<String> imageResponse = gwtInnerServerRequest.post(record.getClientServerName(), GwtTortoiseConst.IMAGE_CLIENT_URI, record.getApplyNo(), new TypeReference<String>() {
                });
                if(CommonConstants.SUCCESS.equals(imageResponse.getCode())) {
                    String returnBase64Str = imageResponse.getData();
                    if (StrUtil.equals(AfsEnumUtil.key(GwtTortoiseImageType.SHRINK_IMAGE), imageReq.getCardType())) {
                        returnBase64Str = SignPictureUtil.shrink(returnBase64Str);
                    }
                    log.info("面签照片获取成功 :{}",imageReq);
                    return GwtTortoiseResponse.successData(returnBase64Str);
                }else{
                    log.info("面签照片获取失败 :{},errMsg:{}",imageReq,imageResponse.getMsg());
                    return GwtTortoiseResponse.err(imageResponse.getMsg());
                }
            }else{
                return GwtTortoiseResponse.err("面签照片获取失败，未知的MaidId");
            }
        }catch (Exception e){
            log.error("面签照片获取异常,",e);
            return GwtTortoiseResponse.err("面签照片获取失败 " + e.getMessage());
        }
    }

    @PostMapping("/tortoise/apis/exposure")
    public GwtTortoiseResponse exposure(@RequestBody GwtTortoiseExposureReq exposureReq) {
        try {
            log.info("敞口信息获取 ==> req : {}",exposureReq);
            String mainId = exposureReq.getMainId();
            Optional<CreditTortoiseRecord> recordOptional= afsCreditTortoiseRecordService.list(
                    Wrappers.<CreditTortoiseRecord>lambdaQuery()
                            .eq(CreditTortoiseRecord::getMainId, mainId)
            ).stream().findAny();
            if(recordOptional.isPresent()) {
                List<TortoiseExposurePerson> personList = new ArrayList<>();
                for (GwtTortoiseExposurePerson person : exposureReq.getData()) {
                    personList.add(TortoiseExposurePerson.builder()
                            .userId(person.getUserId())
                            .card(person.getCard())
                            .company(person.getCompany())
                            .name(person.getName())
                            .phone(person.getPhone())
                            .type(person.getType())
                            .build());
                }
                TortoiseExposureReq innerExposureReq = TortoiseExposureReq.builder()
                        .applyNo(exposureReq.getApplyNo())
                        .mainId(exposureReq.getMainId())
                        .personList(personList)
                        .build();

                IResponse<String> strResp = gwtInnerServerRequest.post(recordOptional.get().getClientServerName(), GwtTortoiseConst.EXPOSURE_CLIENT_URI, innerExposureReq, new TypeReference<String>() {
                });
                if (CommonConstants.SUCCESS.equals(strResp.getCode())) {
                    List<GwtExposureData> exposureDataList = JSONArray.parseArray(strResp.getData(), GwtExposureData.class);
                    log.info("敞口信息获取 ==> resp : {}", strResp.getData());
                    return GwtTortoiseResponse.successData(exposureDataList);
                } else {
                    log.error("敞口信息获取失败：{}", strResp.getMsg());
                    return GwtTortoiseResponse.err(strResp.getMsg());
                }
            }else{
                return GwtTortoiseResponse.err("敞口信息获取失败，未知的MaidId");
            }
        }catch (Exception e){
            log.error("敞口信息获取异常，",e);
            return GwtTortoiseResponse.err("敞口信息获取失败");
        }
    }


}
